const { sqlite3 } = require('../../mysql')
const tools = require('../../utlis/tools')
const config = require('../../config')
const secret = config.jwt_config.secretKey
const expiresIn = config.jwt_config.expiresIn
const jwt = require('jsonwebtoken')
const util = require('util')
const verify = util.promisify(jwt.verify) // 解密


const login = async (ctx) => {
  // console.log('开始登录', ctx.request.body)
  const admin_name = ctx.request.body.username || ctx.request.body.admin_name
  const admin_password = ctx.request.body.password || ctx.request.body.admin_password
  const data = await sqlite3('user').where({
    'username': admin_name
  }).select()
  // console.log('data:', data)
  if (data.length === 0) {
    ctx.body = {
      code: 0,
      data: {},
      meta: {
        status: 500,
        message: '该用户不存在!'
      }
    }
  } else {
    let payload = {
      id: data[0].id,
      admin_name: data[0].username,
      avatar: data[0].avatar,
    }
    // console.log(data[0].id)
    let id = data[0].id
    await sqlite3('user').where({ id })
      .update({ loginTime: tools.GMTtoStr(new Date()) }) // 修改数据库登录时间
    // 生成access-token
    const token = await tools.signToken(payload, secret, expiresIn)
    if (data[0].passwrod === tools.md5(admin_password) && data[0].status === 1) {
      ctx.body = {
        code: 200,
        data: {
          token,
          userInfo: {
            avatar: data[0].avatar,
            roles: data[0].roles,
            username: data[0].username
          }
        },
        meta: {
          status: 200,
          message: `${admin_name}登录成功!`
        }
      }
    } else if (data[0].passwrod === tools.md5(admin_password) && data[0].status === 0) {
      ctx.body = {
        code: 500,
        meta: {
          status: 500,
          message: `${admin_name}账号已被禁用,请联系管理员!`
        }
      }
    } else {
      ctx.body = {
        code: 500,
        meta: {
          status: 500,
          message: '登录密码错误!'
        }
      }
    }
  }
}


const userInfo = async (ctx) => {
  // 获取jwt
  const token = ctx.header.authorization
  if (token) {
    // 解密，获取payload
    const payload = await verify(token.split(' ')[1], secret)
    const data = await sqlite3('user').where({
      username: payload.admin_name,
    }).select()
    // console.log(data);
    if (data) {
      ctx.body = {
        code: 200,
        data: {
          username: data[0].username,
          roles: [data[0].roles],
          avatar: data[0].avatar
        },
        result: true,
      }
    } else {
      ctx.body = {
        result: false,
      }
    }
  }
}


const logout = async (ctx) => {
  ctx.body = {
    code: 200,
    data: 'success'
  }
}


module.exports = { login, userInfo, logout }
